import random
from LocalStateManager import LocalStateManager

class GraphColorStateManager(LocalStateManager):

	kColors = 4
	graphDifficulties = ['graphEasy', 'graphMedium', 'graphHard']
	numberSuccessors = 30
	
	def __init__(self, k):
		self.numberVertices = None
		self.numberEdges = None
		self.graph = []
		self.currentState = []
		super(GraphColorStateManager, self).__init__(k)
	
	def generateInitState(self):
		f = open(GraphColorStateManager.graphDifficulties[self.currentMode])
		#number of edges and vertices
		line = f.readline()
		string = line.split()
		self.currentState = []
		self.numberVertices = int(string[0])
		self.numberEdges = int(string[1])
		random.seed()
		for i in range(self.numberVertices):
			self.currentState += [random.randint(1,self.kColors)]
		for line in f:
			string = line.split()
			self.graph += [(int(string[0]), int(string[1]))]
		#print "Number of vertices: " + str(self.numberVertices)
		#print "Number of edges: " + str(self.numberEdges)
		#print "Starting state: " + str(self.currentState)
	
	#generate successor of the current state
	def generateSuccessors(self):
		k = 0
		random.seed() #init a random generator
		successors = []
		for i in range(GraphColorStateManager.numberSuccessors):
			random.seed()
			copy_state = []
			for j in range(len(self.currentState)):
				k = random.randint(1, self.kColors) 			#choose a random color
				copy_state += [k]
			successors += [copy_state]
		return successors
	
	def modifyState(self, var, value):
		self.currentState[var] = value
		
	#evalutate the state (checking costraints violations)
	def evalutateState(self, state):
		violations = 0
		for i in range(len(state)):
			for j in self.graph:
				#print "vertex: " + str(i)
				#print "edge: " + str(j)
				if i in j and state[j[0]] == state[j[1]]:
					violations+=1
		return violations